package chouxiang.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * Created by tiang on 2018/7/20.
 * 服务消费者
 */
public class Consumer {
    private String address;
    private int port;
    public Consumer(String address, int p){
        this.address = address;
        this.port = p;
    }
    // 获取指定目标的代理类
    public Object getProxy(Class aimClass){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{aimClass}, (proxy, method, args) -> {
            Socket client = new Socket(address, port);
            ObjectOutputStream outputStream = null;
            ObjectInputStream inputStream = null;
            try {
                outputStream = new ObjectOutputStream(client.getOutputStream());
                outputStream.writeObject(aimClass);
                // 因为Method对象无法序列化，这里只能传输方法名和参数类型列表
                // 在服务器端重新获取方法
                outputStream.writeObject(method.getName());
                outputStream.writeObject(method.getParameterTypes());
                outputStream.writeObject(args);
                System.out.println("向服务器请求"+method.getName()+"方法");
                inputStream = new ObjectInputStream(client.getInputStream());
                Object result = inputStream.readObject();
                return result;
            }finally {
                outputStream.close();
                inputStream.close();
            }
        });
    }
}
